package com.chiaching.framwork.core.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.net.URLCodec;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Configuration;

/**
 * 测试环境拦截 fegin 请求参数
 */
@Configuration
@Slf4j
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        byte[] body = template.request().body();
        StringBuilder requestInfo = new StringBuilder();
        requestInfo.append("\n==================  接口请求拦截  =============================\n")
                .append("请求url： ").append(template.url()).append("\n");
        if (null != body) {  // json 请求参数和表单请求参数
            requestInfo = this.buildPrintParam(body, requestInfo);
        }
        if (StringUtils.isNotBlank(template.queryLine())) { // get 请求参数 ?userId=123
            requestInfo.append(template.queryLine()).append("\n");
        }
        requestInfo.append("==================  请求拦截结束  =============================")
                .append("\n");
        log.info("\n{}", requestInfo.toString());
    }


    /**
     * 生成打印的参数
     *
     * @param body
     * @param requestInfo
     * @return
     */
    private StringBuilder buildPrintParam(byte[] body, StringBuilder requestInfo) {
        String bodyParam = this.getBodyString(body);
        if (bodyParam.startsWith("{\"")) {
            requestInfo.append(bodyParam).append("\n");
            return requestInfo;
        }
        if (bodyParam.contains("&")) {
            requestInfo = this.buildRequestParam(requestInfo, bodyParam);
            return requestInfo;
        }
        log.info("其它类型参数：{}", bodyParam);
        return requestInfo;
    }

    /**
     * 参数编码格式化
     *
     * @param body
     * @return
     */
    private String getBodyString(byte[] body) {
        String bodyParam = "";
        try {
            bodyParam = new String(URLCodec.decodeUrl(body));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bodyParam;
    }

    /**
     * 获取请求的参数
     *
     * @param requestInfo
     * @param bodyParam
     * @return
     */
    private StringBuilder buildRequestParam(StringBuilder requestInfo, String bodyParam) {
        String[] split = bodyParam.split("&");
        for (String paramStr : split) {
            String[] split1 = paramStr.split("=");
            if (null != split1 && split1.length >= 2) {
                requestInfo.append(split1[0]).append(":").append(split1[1]).append("\n");
            }
        }
        return requestInfo;
    }
}